import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:dear_lottery/tools/models/DL_DataViewModel.dart';
import 'package:dear_lottery/tools/models/DL_LottoModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';

import '../../Results/DL_resultDetailPageVC.dart';
import '../../tools/DL_Segment.dart';
import '../../tools/DL_drawNumbersView.dart';

class DL_resultView_homePage extends StatefulWidget {
  DL_resultView_homePage({
    super.key,
    this.pageController,
    this.onTabChanged,
  });
  PageController? pageController;
  Function(int)? onTabChanged;
  @override
  State<DL_resultView_homePage> createState() => _DL_resultView_homePageState();
}

class _DL_resultView_homePageState extends State<DL_resultView_homePage> {
  late var onePMModels = [];
  late var sixPMModels = [];
  late var eightPMModels = [];
  late var otherPMModels = [];
  int currentIndex = 0;

  late var lottoModel = DL_LottoModel();
  var _numbersMap = {}; //号码
  var _drawDateString = ''; //开奖日期
  var _segmentType = '1PM';

  @override
  void initState() {
    super.initState();

    _configData();
  }

  void _configData() {
    onePMModels = DL_DataViewModel().DL_onePM_resultsModels;
    sixPMModels = DL_DataViewModel().DL_sixPM_resultsModels;
    eightPMModels = DL_DataViewModel().DL_eightPM_resultsModels;
    otherPMModels = DL_DataViewModel().DL_others_resultsModels;
    _onTabChanged(currentIndex);
  }

  void _onTabChanged(int index) {
    switch (index) {
      case 0:
        lottoModel = onePMModels[0];
        break;
      case 1:
        lottoModel = sixPMModels[0];
        break;
      case 2:
        lottoModel = eightPMModels[0];
        break;
      case 3:
        lottoModel =
            otherPMModels.isNotEmpty ? otherPMModels[0] : DL_LottoModel();
        break;
      default:
    }
    currentIndex = index;

    //代表有数据
    if (lottoModel.id != null) {
      _configItemData();
    } else {
      setState(() {});
    }
  }

  void _configItemData() {
    DateTime drawDateTimeUTC = DateTime.parse(lottoModel.draw_date!);
    var drawDate = DateFormat('EEE, MMM d, y').format(drawDateTimeUTC);
    _drawDateString = '$_segmentType,$drawDate';

    if (lottoModel.first_prize_num!.isNotEmpty) {
      String firstPrizeNum = lottoModel.first_prize_num![0];
      List<String> charArray = firstPrizeNum.split('');
      var balls = [];
      for (var i = 0; i < charArray.length; i++) {
        var ball = {
          'number': charArray[i],
          'isRight': false,
          'isNormal': true
        }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
        balls.add(ball);
      }
      var title = '1st Prize';
      _numbersMap = {'title': title, 'balls': balls};
    }

    setState(() {});
  }

  //
  void _goToResultsPage() {
    var page = widget.pageController!;
    page.jumpToPage(1);
  }

  void _goToDetailPage(var model) {
    if (lottoModel.id == null) {
      return;
    }
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DL_ResultDetailPageVC(
                  lottoModel: model,
                )));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // height: 100,
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.only(top: 10, bottom: 10),
      decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2), // 阴影颜色
              spreadRadius: 1, // 扩散半径
              blurRadius: 10, // 模糊半径
              offset: const Offset(0, 1), // 阴影偏移
            ),
          ],
          color: Colors.white,
          borderRadius: const BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [
          Container(
            height: 25,
            // alignment: Alignment.center,
            padding:
                const EdgeInsets.only(left: 22, top: 4, right: 25, bottom: 4),
            // margin: EdgeInsets.only(left: 15, right: 15),
            decoration: const BoxDecoration(
                // color: KaL_Config.AL_MainColor.withOpacity(0.8),
                color: Colors.black,
                borderRadius: BorderRadius.all(Radius.circular(25 * 0.5))),
            child: const Text(
              'WINNING NUMBERS',
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 12),
            ),
          ),
          const SizedBox(height: 15),
          DlSegment(
            sliderColor: HexColor('#ff3433'),
            backgroundColor: HexColor('#f5f5f5'),
            onSegmentChange: (index, value) => {
              debugPrint('value---$value,index---$index'),
              _segmentType = value,
              _onTabChanged(index),
              if (widget.onTabChanged != null) {widget.onTabChanged!(index)}
            },
          ),
          const SizedBox(height: 10),
          Text(
            lottoModel.draw_date == null ? 'No Data' : _drawDateString,
            style: const TextStyle(
              fontWeight: FontWeight.w400,
              fontSize: 16,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 10),
          lottoModel.id == null ? Container() : drawingNumbersView(),
          const SizedBox(height: 15),
          viewDetailBtn(),
          const SizedBox(height: 10),
          historyResultBtn(),
        ],
      ),
    );
  }

  Widget drawingNumbersView() {
    return Container(
      margin: const EdgeInsets.all(10),
      child: DL_drawNumbersView(data: _numbersMap),
    );
  }

  Widget viewDetailBtn() {
    double btnH = 40;
    return GestureDetector(
      onTap: () {
        debugPrint('_gotoHistoryPage()');
        _goToDetailPage(lottoModel);
      },
      child: Container(
        height: btnH,
        width: 300,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: DL_Config.DL_MainColor,
            borderRadius: BorderRadius.all(Radius.circular(btnH * 0.5))),
        child: const Text(
          'VIEW FULL DETAILS',
          style: TextStyle(
              fontSize: 15, fontWeight: FontWeight.w600, color: Colors.white),
        ),
      ),
    );
  }

  Widget historyResultBtn() {
    double btnH = 40;
    return GestureDetector(
      onTap: () {
        debugPrint('_goToResultsPage()');
        _goToResultsPage();
      },
      child: Container(
        height: btnH,
        width: 300,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            // color: HexColor('##222529'),
            borderRadius: BorderRadius.all(Radius.circular(btnH * 0.5))),
        child: Text(
          'PREVIOUS RESULTS',
          style: TextStyle(
            fontSize: 15,
            fontWeight: FontWeight.w600,
            color: DL_Config.DL_MainColor,
          ),
        ),
      ),
    );
  }
}
